package com.wwwarehouse.dubbo.client;

import com.alibaba.dubbo.config.*;
import com.alibaba.dubbo.config.utils.ReferenceConfigCache;
import com.alibaba.dubbo.rpc.service.GenericService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class MyGenericService {
    @Autowired
    ApplicationConfig applicationConfig;

    @Autowired
    RegistryConfig registryConfig;

    @Autowired
    ConsumerConfig consumerConfig;

    @Autowired
    ProtocolConfig protocolConfig;

    public Object invoke(String interfaceClass, String methodName, Object[] invokeParams) {
        ReferenceConfig<GenericService> reference = new ReferenceConfig<>();
        reference.setApplication(applicationConfig);
        reference.setRegistry(registryConfig);
        reference.setConsumer(consumerConfig);
        // 接口名
        reference.setInterface(interfaceClass);
        // 声明为泛化接口
        reference.setGeneric(true);
//        reference.setVersion(requestParam.getVersion() + "." + versionBranch);
//        reference.setGroup(requestParam.getGroup());
        reference.setRetries(0);
//        reference.setTimeout(requestParam.getTimeOut());
        reference.setAsync(false);
        // 协议
        reference.setProtocol(protocolConfig.getName());

        ReferenceConfigCache cache = ReferenceConfigCache.getCache("wwwarehouseGenerator",
                ReferenceKeyGenerator.keyGenerator);

        GenericService genericService = cache.get(reference);

        if (genericService == null) {
            cache.destroy(reference);
            log.error("null");
        }

        return genericService.$invoke(methodName, null, invokeParams);
    }
}
